<!-- 最新版本，要求可以上传图标 -->
<template>
  <div class="sort">
    <div class="video-tree">
      <el-tree
        class="body-tree"
        :data="dataTree"
        default-expand-all
        :props="defaultProps"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        node-key="id"
      ></el-tree>
    </div>
    <div>
      <el-form
        ref="formRef"
        :model="dataForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="上级分类：" prop="parentid">
          <el-select
            :disabled="disabled"
            class="select-width"
            v-model="dataForm.parentid"
            placeholder="请选择上级分类"
          >
            <el-option
              v-for="item in parentIDList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前分类：" prop="name">
          <el-input
            v-model="dataForm.name"
            placeholder="请输入当前分类"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类地址：" prop="url">
          <el-input
            v-model="dataForm.url"
            placeholder="请输入当前分类地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图标：">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序：" prop="sort" class="diff-input">
          <el-input-number v-model="dataForm.sort" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-switch
            v-model="dataForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <div style="line-height: 54px; text-align: center">
          <el-button type="success" plain @click="addSort">新增分类</el-button>
          <el-button
            type="danger"
            plain
            @click="deleteSort"
            :disabled="editDisabled"
            >删除分类</el-button
          >
          <el-button type="primary" plain @click="editSort">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
// import {
//   getTree,
//   treeAdd,
//   treeUpdate,
//   treeDelete,
// } from "@/api/video/basicInformationApi.js";
export default {
  name: "sort",
  components: {},
  props: {
    dialogVisibleUse: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dataForm: {
        parentid: undefined,
        id: undefined,
        name: undefined,
        sort: 0,
        status: "1",
        url: "",
        icon: "",
      },
      dataTree: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      parentIDList: [],
      disabled: false,
      editDisabled: true,
      rules: {
        parentid: [
          { required: true, message: "请选择上级分类", trigger: "change" },
        ],
        name: [
          { required: true, message: "请输入当前分类", trigger: "change" },
        ],
        sort: [{ required: true, message: "请选择排序", trigger: "change" }],
      },
      // 图片上传
      imageUrl: "", //用于页面展示（blob的）
      queryImageUrl: "", // 用于接口上传（64的）
    };
  },
  mounted() {
    this.getTree();
    this.parentGetTree();
  },
  methods: {
    // 图片上传逻辑
    async handleChange(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.image64(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 图片blob转成base64格式
    image64(blobUrl) {
      const reader = new FileReader();
      reader.readAsDataURL(blobUrl);
      // 监听读取完成事件
      reader.onload = () => {
        // this.queryImageUrl = reader.result.replace(
        //   "data:image/png;base64,",
        //   ""
        // );
        this.queryImageUrl = reader.result;
        this.dataForm.icon = this.queryImageUrl;
      };
    },
    // 图片blob转成file格式
    async fileImg(blobUrl) {
      console.log(blobUrl, "这是要传唤的Blob URL");
      try {
        // 使用fetch API获取Blob对象
        const response = await fetch(blobUrl);
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        const blob = await response.blob();
        // 创建一个新的File对象
        const file = new File([blob], "image.png", {
          type: "image/png",
          lastModified: Date.now(),
        });
        return file;
        // // 现在可以使用file对象，比如将它添加到FormData中用于上传
        // const formData = new FormData();
        // formData.append("file", file);
        // console.log(formData, "FormData对象已包含文件");
        // return formData;
      } catch (error) {
        console.error("Error fetching blob:", error);
        throw error; // 可选：重新抛出错误以便上层调用者可以处理
      }
    },
    //表单重置
    rest() {
      this.dataForm = {
        parentid: undefined,
        id: undefined,
        name: undefined,
        sort: 0,
        status: "1",
        url: "",
        icon: "",
      };
      this.imageUrl = "";
      this.editDisabled = true;
      this.disabled = false;
      this.$refs.formRef.resetFields();
    },
    //树形数据
    getTree() {
      // getTree().then((res) => {
      //   if (res.state == 1) {
      //     this.dataTree = [res.data];
      //   }
      // });
    },
    handleNodeClick(data) {
      if (data.id == "0") {
        this.rules.parentid[0].required = false;
        this.editDisabled = true;
      } else {
        this.rules.parentid[0].required = true;
        this.editDisabled = false;
      }
      if (data.finallevel == "1") {
        this.disabled = false;
      } else {
        this.disabled = true;
      }
      this.dataForm = {
        parentid: data.parentid,
        id: data.id,
        name: data.name,
        sort: data.sort,
        status: data.status,
        url: data.url,
        icon: data.icon,
      };
      this.imageUrl = data.icon;
    },
    parentGetTree() {
      // getTree({
      //   level: 1,
      // }).then((res) => {
      //   if (res.state == 1) {
      //     this.parentIDList = this.treeToArr([res.data]);
      //   }
      // });
    },
    //删除分类
    deleteSort() {
      this.$confirm(" 是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // treeDelete({ id: this.dataForm.id }).then((res) => {
          //   if (res.state == 1) {
          //     this.$message.success("删除成功！");
          //     this.rest();
          //     this.getTree();
          //     this.parentGetTree();
          //   } else {
          //     this.$message.error(res.message);
          //   }
          // });
        })
        .catch(() => {});
    },
    //修改分类
    editSort() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.dataForm.id) {
            // treeUpdate(this.dataForm).then((res) => {
            //   if (res.state == 1) {
            //     this.$message.success("修改成功！");
            //     this.getTree();
            //     this.parentGetTree();
            //   }
            // });
          } else {
            // treeAdd(this.dataForm).then((res) => {
            //   if (res.state == 1) {
            //     this.$message.success("新增成功！");
            //     this.rest();
            //     this.getTree();
            //     this.parentGetTree();
            //   }
            // });
          }
        }
      });
    },
    //新增分类
    addSort() {
      this.rest();
    },
    treeToArr(data) {
      return data.reduce((res, { id, name, level, children }) => {
        res.push({ id, level, name });
        if (children && children.length) {
          res = [...res, ...this.treeToArr(children, id)];
        }
        return res;
      }, []);
    },
  },
};
</script>
<style lang="scss" scoped>
.sort {
  width: 100%;
  display: flex;
  gap: 12px;
  padding: 12px;
  .video-tree {
    padding-right: 20px;
    width: 35%;
    border-right: 1px solid #ccc;
    height: 38vh;
    overflow: auto;
    scrollbar-width: none;
  }
  .diff-input ::v-deep .el-input__inner {
    width: 131px !important;
  }
  // 图片上传
  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader ::v-deep .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
